import Character from '../base/character';
import DataBus from '../databus';
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render';

const databus = new DataBus();

const ENEMY_WIDTH = 48;   // 敌人宽度
const ENEMY_HEIGHT = 64;  // 敌人高度
const MOVE_SPEED = 1;     // 移动速度降低为原来的一半

// 敌人类型和性格
const ENEMY_TYPE = {
  GOAT: 1,  // 鹿
  PIG: 2    // 野猪
};

const PERSONALITY = {
  AGGRESSIVE: 'aggressive', // 激进型，喜欢近身战斗
  CAUTIOUS: 'cautious',    // 谨慎型，保持距离
  TIMID: 'timid'          // 胆小型，容易逃跑
};

export default class Enemy extends Character {
  constructor(enemyType = 1, canvas = null) {
    const imgSrc = enemyType === 1 ? 'images/enemy1.png' : 'images/enemy2.png';
    super(imgSrc, ENEMY_WIDTH, ENEMY_HEIGHT, ENEMY_WIDTH, canvas);

    // 敌人特有属性
    this.isDying = false;      // 标记敌人是否处于死亡状态
    this.blinkCount = 0;       // 闪烁计数器
    this.enemyType = enemyType;

    // 根据类型决定性格
    this.personality = enemyType === 1 ? 
      (Math.random() > 0.5 ? PERSONALITY.AGGRESSIVE : PERSONALITY.CAUTIOUS) : 
      PERSONALITY.AGGRESSIVE;

    // 设置敌人属性
    this.maxHp = 60;
    this.hp = this.maxHp;
    this.attack = enemyType === 1 ? 8 : 12;
    this.defense = enemyType === 1 ? 3 : 5;
    this.expValue = enemyType === 1 ? 20 : 35;
    
    // 设置敌人特有的帧间隔和攻击属性
    this.frameInterval = 8;  // 比玩家慢一些
    this.attackInterval = 90;
    
    // 设置攻击区域属性
    this.attackRange = enemyType === 1 ? 80 : 100;   // 攻击范围
    this.attackWidth = enemyType === 1 ? 60 : 80;    // 攻击区域宽度
    this.attackHeight = this.height;                  // 攻击区域高度与角色高度相同
    
    // 行为模式
    this.behaviorTimer = 0;
    this.behaviorInterval = 60; // 每60帧改变一次行为
    this.behavior = 'chase';   // 初始行为：追击
    this.lastBehaviorChange = 0; // 上次行为改变的时间
    this.minBehaviorDuration = 30; // 最小行为持续时间

    // 根据性格设置距离阈值
    if (this.personality === PERSONALITY.AGGRESSIVE) {
      this.chaseDistance = 300;   // 减小追击距离，使战斗更紧凑
      this.retreatDistance = 20;  // 减小后退距离，更容易近身战斗
      this.speed = MOVE_SPEED * 1.2; // 保持较快的移动速度
    } else {
      this.chaseDistance = 200;   // 减小追击距离
      this.retreatDistance = 100; // 减小后退距离
      this.speed = MOVE_SPEED;
    }
  }

  init(type, x, y) {
    // 更新敌人类型和相关属性
    this.enemyType = type;
    
    // 根据类型更新图片
    this.img.src = this.enemyType === ENEMY_TYPE.GOAT ? 'pics/goat.png' : 'pics/pig.png';
    
    // 设置位置
    this.x = x;
    this.y = y;
    
    // 重置状态
    this.visible = true;
    this.currentFrame = 0;
    this.hp = this.maxHp;
    this.lastBehaviorChange = 0;
    this.isKnockedBack = false;
    this.knockbackRecoveryTime = 0;
    this.isDying = false;
    this.blinkCount = 0;
    this.isAlarmed = false;
    this.alarmTimer = 0;
    this.fleeTarget = null;
    
    // 根据类型更新属性
    if (this.enemyType === ENEMY_TYPE.GOAT) {
      this.attack = 5;
      this.defense = 2;
      this.expValue = 15;
      this.attackRange = 60;
      this.attackWidth = 50;
      this.visionRange = 300; // 鹿的视野更好
      this.fleeSpeed = MOVE_SPEED * 1.5; // 鹿逃跑更快
      // 鹿更容易受惊
      this.personality = Math.random() > 0.7 ? PERSONALITY.CAUTIOUS : PERSONALITY.TIMID;
    } else {
      this.attack = 12;
      this.defense = 5;
      this.expValue = 30;
      this.attackRange = 90;
      this.attackWidth = 70;
      this.visionRange = 250; // 野猪视野一般
      this.fleeSpeed = MOVE_SPEED * 1.2; // 野猪逃跑较快
      // 野猪更具攻击性
      this.personality = Math.random() > 0.3 ? PERSONALITY.AGGRESSIVE : PERSONALITY.CAUTIOUS;
    }
    
    // 根据性格更新行为参数
    switch (this.personality) {
      case PERSONALITY.AGGRESSIVE:
        this.chaseDistance = 150;  // 减少为150
        this.retreatDistance = 30;
        this.speed = MOVE_SPEED * 1.1;
        break;
      case PERSONALITY.CAUTIOUS:
        this.chaseDistance = 120;  // 减少为120
        this.retreatDistance = 80; // 减少后退距离
        this.speed = MOVE_SPEED;
        break;
      case PERSONALITY.TIMID:
        this.chaseDistance = 100;  // 减少为100
        this.retreatDistance = 80; // 减少后退距离
        this.speed = MOVE_SPEED * 0.9;
        this.alarmDuration = 180;  // 减少警戒时间
        break;
    }
    
    console.log('Enemy initialized:', {
      type: this.enemyType,
      position: {x: this.x, y: this.y},
      personality: this.personality,
      stats: {
        attack: this.attack,
        defense: this.defense,
        speed: this.speed
      }
    });
  }

  // 移动方法
  moveTowards(dx, dy, distance) {
    if (distance === 0) return;
    
    // 计算移动向量
    const moveX = (dx / distance) * this.speed;
    const moveY = (dy / distance) * this.speed;
    
    // 应用移动
    super.move(moveX, moveY, 1);
  }

  // 重写takeDamage方法，添加死亡处理
  takeDamage(damage, attacker) {
    if (this.isDying) return;

    // 调用父类的takeDamage方法，确保显示伤害动画
    const actualDamage = super.takeDamage(damage, attacker);
    
    // 闪烁效果
    this.isBlinking = true;
    setTimeout(() => {
      this.isBlinking = false;
    }, 200);
    
    if (this.hp <= 0) {
      if (databus.player) {
        databus.player.gainExp(this.expValue);
        console.log('Player gained exp:', this.expValue);
      }
      this.isDying = true;
      this.blinkCount = 0;
      databus.score += this.enemyType === 1 ? 10 : 20;
    }
    
    return actualDamage;
  }

  // 自动攻击
  autoAttack() {
    if (this.isDying || !databus.player || databus.gameOver || this.isKnockedBack) return;

    if (++this.attackTimer >= this.attackInterval) {
      this.attackTimer = 0;
      
      // 使用新的攻击区域检测方法
      if (this.isTargetInAttackRange(databus.player)) {
        // 计算是否暴击 (10%几率)
        const isCritical = Math.random() < 0.1;
        const damage = isCritical ? Math.floor(this.attack * 1.5) : this.attack;
        
        // 对玩家造成伤害并触发击退
        databus.player.takeDamage(damage, this);
        
        // 添加视觉反馈
        if (databus.player.visible) {
          databus.player.blinkCount = 0;
          databus.player.isBlinking = true;
          
          // 3帧后停止闪烁
          setTimeout(() => {
            databus.player.isBlinking = false;
          }, 3 * 16); // 假设游戏运行在约60FPS
        }
        
        // 显示伤害数字
        this.showDamageNumber(databus.player, damage, isCritical);
        
        console.log('Enemy attacked player for', damage, 'damage', isCritical ? '(CRITICAL!)' : '');
      }
    }
  }

  // 显示对目标造成的伤害
  showDamageToTarget(target, damage, isCritical) {
    // 使用目标的showDamageNumber方法来显示伤害
    if (target && typeof target.showDamageNumber === 'function') {
      target.showDamageNumber(damage, isCritical);
    }
  }

  update() {
    // 如果敌人处于死亡状态
    if (this.isDying) {
      // 增加闪烁计数
      this.blinkCount++;
      
      // 每5帧切换一次可见性（闪烁效果）
      this.visible = (this.blinkCount % 10) < 5;
      
      // 闪烁6次（约30帧）后移除敌人
      if (this.blinkCount > 30) {
        databus.removeEnemey(this);
        return; // 直接返回，不再执行其他逻辑
      }
      
      // 在死亡过程中不执行其他逻辑
      return;
    }
    
    const player = databus.player;
    if (!player) return;

    super.update();

    // 如果正在被击退，不执行移动逻辑
    if (this.isKnockedBack) {
      return;
    }

    // 计算与玩家的距离
    const dx = player.x - this.x;
    const dy = player.y - this.y;
    const distance = this.getDistanceTo(player);
    
    // 更新朝向 - 确保朝向与移动方向一致
    this.direction = dx > 0 ? 'right' : 'left';
    
    // 检查是否需要改变行为
    if (databus.frame - this.lastBehaviorChange > this.minBehaviorDuration) {
      // 根据性格和距离决定行为
      if (distance > this.chaseDistance) {
        this.behavior = 'chase'; // 距离太远时追击
      } else if (distance < this.retreatDistance) {
        // 激进型敌人在血量高时不会后退
        if (this.personality === PERSONALITY.AGGRESSIVE && this.hp > this.maxHp * 0.3) {
          this.behavior = 'chase';
        } else {
          this.behavior = 'retreat'; // 距离太近时后退
        }
      } else {
        // 在合适距离时，激进型继续追击，谨慎型保持距离
        this.behavior = this.personality === PERSONALITY.AGGRESSIVE ? 'chase' : 'patrol';
      }
      this.lastBehaviorChange = databus.frame;
    }
    
    // 根据行为模式移动
    if (this.behavior === 'chase') {
      // 追击玩家
      this.moveTowards(dx, dy, distance);
    } else if (this.behavior === 'retreat') {
      // 远离玩家
      this.direction = dx > 0 ? 'left' : 'right'; // 后退时朝向相反
      this.moveTowards(-dx, -dy, distance);
    } else if (this.behavior === 'patrol') {
      // 在当前位置附近巡逻
      const patrolX = Math.sin(databus.frame / 30) * this.speed * 0.5;
      const patrolY = Math.cos(databus.frame / 45) * this.speed * 0.3;
      
      this.x += patrolX;
      this.y += patrolY;
      
      // 边界检查
      this.x = Math.max(0, Math.min(SCREEN_WIDTH - this.width, this.x));
      this.y = Math.max(0, Math.min(SCREEN_HEIGHT - this.height, this.y));
      
      // 根据巡逻方向更新朝向
      if (patrolX > 0) {
        this.direction = 'right';
      } else if (patrolX < 0) {
        this.direction = 'left';
      }
    }
    
    // 自动攻击
    this.autoAttack();
  }
}